<template>
  <div class="container">
    <editPageNew
      ref="editPage"
      :showMore="false"
      :rightBtnArr="rightBtnArr"
      :creatInfo="creatInfo"
      showTopTitle
    >
      <template slot="editPageTitle">
        <span class="title">流程配置</span>
      </template>
      <div class="plan-title">
        <div class="name">
          <span>{{ basicFormData.processName }}</span>
        </div>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item name="0">
          <template slot="title"> 基本信息 </template>
          <editForm
            class="info-data"
            :formConfig="basicConfig"
            ref="basicForm"
            :formData="basicFormData"
          ></editForm>
        </el-collapse-item>
        <el-collapse-item name="1">
          <template slot="title"> 节点配置 </template>
          <div class="node-info">
            <el-row style="height: 100%">
              <el-col :span="6" class="border-radius">
                <div class="left">
                  <div class="label-text">节点列表</div>
                  <baseTable
                    :class="{
                      'work-type': true,
                      'show-item': showItem,
                    }"
                    :tableSetting="leftTable"
                    ref="nodeLeftTable"
                  ></baseTable>
                </div>
              </el-col>
              <el-col :span="18" class="border border-radius">
                <div class="right">
                  <div class="label-text">节点信息</div>
                  <editForm
                    :formConfig="nodeConfig0"
                    ref="nodeForm0"
                    :formData="nodeFormData0"
                  ></editForm>
                  <span class="label-table">流程插件</span>
                  <editTableNew
                    class="right-table"
                    :tableSetting="rightTable"
                    :hideBtn="false"
                    ref="nodeRightTable"
                    :tableData="rightTableData"
                  >
                  </editTableNew>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <dialogPublic
      width="1000px"
      title="编辑"
      :show.sync="showDialog"
      v-if="showDialog"
      @doSubmit="doSubmit"
      @doClose="() => (showDialog = false)"
    >
      <editForm
        class="node"
        :formConfig="nodeConfig"
        ref="nodeForm"
        :positiveSequence="true"
        :formData="nodeFormData"
      >
        <template #userConfig="{ editFormInfo }"> 
          <tableList :userConfig="editFormInfo.userConfig" ref="tableList"></tableList>
        </template>
      </editForm>
      <el-row class="node">
        <el-col :span="5">
          <div class="grid-content bg-purple">节点处理人（最终选择组织）</div>
        </el-col>
        <el-col :span="19">
          <el-select
            class="w100"
            v-model="organizationIndex"
            multiple
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in organization"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
    </dialogPublic>
  </div>
</template>
<script>
import { queryPostList } from "@/api/common";
import {
  queryInfoById,
  addOrSaveInfo,
  deleteInfo,
} from "@/api/businessConfigurationManagement/processConfiguration.js";
import tableList from "./tableList.vue";
export default {
  components: {tableList},
  data() {
    return {
      id: "",
      workflowPluginId: "",
      workflowPluginType: "",
      creatInfo: {}, // 右下角创建信息
      activeNames: ["0", "1"],
      showItem: true, //默认显示列表左侧第一条数据
      showDialog: false, //编辑
      // showStaff: false, // 选择组件
      handler: [], //选人
      post: [], //岗位
      handlerArr: [],
      postArr: [],
      organization: [], //组织下拉待选择
      organizationIndex: [], //组织已选择数据下标
      organizationArr: [], //组织已选择数据
      // 基本信息表单
      basicConfig: {
        labelWidth: "140px",
        itemArr: [
          {
            label: "模板组编号",
            prop: "setCode",
            type: "text",
            span: 8,
            required: true,
            disabled: true,
          },
          {
            label: "所属业务模块",
            prop: "moduleCode",
            type: "text",
            span: 8,
            disabled: true,
          },
          {
            label: "模板编号",
            prop: "processCode",
            type: "text",
            span: 8,
            required: true,
            disabled: true,
          },
          {
            label: "模板名称",
            prop: "processName",
            type: "text",
            span: 8,
            required: true,
            disabled: true,
          },
          {
            label: "回调接口（中缀）",
            prop: "callbackController",
            type: "text",
            span: 8,
            required: true,
            disabled: true,
          },
          {
            label: "应用编号",
            prop: "appCode",
            type: "text",
            span: 8,
            disabled: true,
          },
        ],
      },
      // 基本信息表单数据
      basicFormData: {},
      // 节点配置表单
      nodeConfig0: {
        labelWidth: "180px",
        itemArr: [
          {
            label: "节点名称",
            prop: "nodeName",
            type: "text",
            span: 10,
            disabled: true,
          },
          {
            label: "节点编码",
            prop: "nodeCode",
            type: "text",
            span: 10,
            disabled: true,
          },
        ],
      },
      // 节点配置表单数据
      nodeFormData0: {},
      // 节点配置表单
      nodeConfig: {
        labelWidth: "180px",
        itemArr: [
          {
            label: "插件类型",
            prop: "type",
            type: "select",
            span: 12,
            required: true,
            disabled: true,
            selectOption: this.$store.getters["dirtData"](
              "workflow_plugin_type"
            ),
          },
          {
            label: "插件状态",
            prop: "enabled",
            trigger: "change",
            type: "radio",
            span: 12,
            required: true,
            radioOption: [
              {
                value: 1,
                label: "已启用",
              },
              {
                value: 0,
                label: "已停用",
              },
            ],
            methods: (val) => {
              this.changeEnabled(val.value);
            },
          },
          {
            label: "插件接口url",
            prop: "accessUrl",
            filterable: true,
            type: "autocomplete",
            span: 24,
            required: true,
            placeholder: "后缀包含/",
            selectOption: [],
          },
          {
            label: "插件描述",
            prop: "description",
            type: "textarea",
            span: 24,
            rows: 3,
            placeholder: "请输入",
          },
          {
            label: "节点处理人",
            prop: "memberName",
            propArr: "memberNameArr",
            idsStr: "memberAccount",
            orgStr: "classOrgStr",
            orgNameStr: "classOrgName",
            orgIdStr: "classOrgId",
            multiple: true, //是否多选
            allowCreate: true, //是否允许创建条目
            option: this.handler,
            type: "user-select", //类型
            trigger: "change",
            isHide: false,
            methods: (val) => {
              this.handlerArr = [];
              val.forEach((item) => {
                let obj = {
                  code: item.id || item.value,
                  name: item.name || item.label,
                  type: 0,
                  workflowId: this.id,
                  workflowPluginId: this.workflowPluginId,
                };
                this.handlerArr.push(obj);
              });
            },
            span: 24,
          },
          {
            label: "节点处理人（岗位）",
            prop: "node4",
            type: "select-search",
            linkage: true,
            multiple: true,
            collapseTags: true,
            clearable: true,
            seleteOption: this.post,
            methods: async (val) => {
              this.postArr = [];
              val.forEach((item) => {
                let obj = {
                  code: item.value,
                  name: item.label,
                  type: 2,
                  workflowId: this.id,
                  workflowPluginId: this.workflowPluginId,
                };
                this.postArr.push(obj);
              });
            },
            span: 24,
          },
          {
            label: "节点人员配置",
            prop: "userConfig",
            type: "text",
            span: 24,
            rows: 3,
            placeholder: "请输入",
          },
          {
            label: "节点处理人（组织）",
            prop: "workTeamName", //多选时，字段要为数组类型
            propArr: "workTeamNameArr",
            idsStr: "workTeam",
            multiple: true, //是否多选
            option: [],
            allowCreate: true, //是否允许创建条目
            type: "dept-select", //类型
            trigger: "change",
            methods: (val) => {
              let value = this.organization.length;
              val.forEach((item) => {
                let obj = {
                  code: item.id || item.value,
                  name: item.name || item.label,
                  type: 1,
                  workflowId: this.id,
                  workflowPluginId: this.workflowPluginId,
                  value: value,
                };
                this.organization.push(obj);
                this.organizationIndex.push(value);
                value++;
              });
            },
            span: 24,
          },
        ],
      },
      // 节点配置表单数据
      nodeFormData: {},
      // 左侧表格
      leftTable: {
        indexShow: false, // 序号显示
        height: 399,
        column: [
          {
            label: "节点名称",
            prop: "nodeName",
            required: true,
            showTooltip: false,
          },
          {
            label: "插件数量",
            width: "80px",
            prop: "pluginSize",
            required: true,
            showTooltip: false,
          },
        ],
        data: [],
        rowClick: async (row) => {
          this.nodeFormData0 = row;
          this.rightTable.data = row.configureWorkflowPluginDTOList;
          this.showItem = false;
        },
      },
      rightTableData: [],
      // 右侧表格
      rightTable: {
        title: "",
        select: false,
        addMethons: true,
        height: 336,
        btnArr: [],
        data: [],
        column: [
          {
            label: "插件类型",
            prop: "type",
            type: "disableText",
            width: 140,
            formatter: (data, row) => {
              let types = this.$store.getters["dirtData"](
                "workflow_plugin_type"
              );
              let val = row.type;
              let obj = types.find((i) => i.value == val);
              return obj ? obj.label : val;
            },
          },
          {
            label: "插件接口url",
            prop: "accessUrl",
            type: "disableText",
          },
          {
            label: "插件描述",
            prop: "description",
            type: "disableText",
          },
          {
            label: "状态",
            prop: "enabled",
            width: 80,
            type: "switch",
            activeText: "启用",
            inactiveText: "停用",
            methods: (row, val) => {
              if (!row.accessUrl) {
                row.enabled = 0;
                this.$message.warning("插件接口url未填写，不能启用");
              }
            },
          },
        ],
        buttonArr: [
          {
            name: "编辑",
            icon: "icon-a-xiugaibianji",
            isShow: (row) => {
              return true;
            },
            methods: (row) => {
              if (row.enabled == 1) {
                this.nodeConfig.itemArr[2].required = true;
              } else {
                this.nodeConfig.itemArr[2].required = false;
              }
              this.workflowPluginId = row.id;
              this.workflowPluginType = row.type;
              this.nodeFormData = row;
              this.setStaffData(row.configureWorkflowStaffList);
              this.showDialog = true;
            },
          },
        ],
        data: [],
      },
    };
  },
  computed: {
    // 操作按钮
    rightBtnArr() {
      let arr = [
        {
          text: "保存",
          icon: "icon-baocun",
          disabled: !this.$store.getters.isBtnAuth("save"),
          content: "未授权的功能",
          hide: false,
          methods: () => {
            this.save();
          },
        },
        {
          text: "删除",
          icon: "icon-shanchu",
          disabled: !this.$store.getters.isBtnAuth("delete"),
          content: "未授权的功能",
          hide: false,
          methods: () => {
            this.delete();
          },
        },
      ];
      return arr;
    },
  },
  created() {
    this.setPostSelectData();
    this.init();
  },
  mounted() {},
  methods: {
    // 初始化信息
    async init() {
      this.id = this.$route.query.id;
      this.getDetails();
    },
    //获取详情信息
    async getDetails() {
      let val = { id: this.id };
      let { data } = await queryInfoById(val);
      let { createByName, createTime } = data;
      this.creatInfo = { createByName, createTime };
      this.nodeConfig.itemArr[2].selectOption = this.$store.getters["dirtData"](
        "workflow_common_plugin"
      );
      this.basicFormData = data;
      this.leftTable.data = this.basicFormData.configureWorkflowNodeDTOList;
      this.nodeFormData0 = this.basicFormData.configureWorkflowNodeDTOList[0];
      this.rightTable.data = this.basicFormData.configureWorkflowNodeDTOList[0].configureWorkflowPluginDTOList;
    },
    // 改变必填项
    changeEnabled(val) {
      let rules = {};
      if (val == 1) {
        rules.accessUrl = [
          {
            required: true,
            message: "请输入插件接口url",
            trigger: "blur",
          },
        ];
      } else {
        rules.accessUrl = [{}];
      }
      this.$refs.nodeForm.setItemArrRules(rules);
    },
    // 编辑弹框确定
    async doSubmit() {
      if (this.organizationIndex.length) {
        this.organizationIndex.forEach((item) => {
          let obj = this.organization.find((objItem) => {
            return objItem.value == item;
          });
          if (obj) {
            this.organizationArr.push(obj);
          }
        });
      } else {
        this.organizationArr = [];
      }
      setTimeout(async () => {
        let data = await this.$refs.nodeForm.getFormData();
        data.userConfig = await this.$refs.tableList.getTableData();
        delete data.memberAccount;
        delete data.memberName;
        delete data.memberNameArr;
        delete data.node4;
        delete data.workTeam;
        delete data.workTeamName;
        delete data.workTeamNameArr;
        delete data.undefined;
        this.showDialog = false;
        this.rightTable.data.forEach((item, index) => {
          if (item.type == this.workflowPluginType) {
            this.rightTable.data[index] = data;
            this.rightTable.data[index].configureWorkflowStaffList = [
              ...this.handlerArr,
              ...this.postArr,
              ...this.organizationArr,
            ];
            this.$refs.nodeRightTable.setTableData(this.rightTable.data);
          }
        });
      });
    },
    // 设置选岗位数据
    setPostSelectData() {
      let arr = [];
      let info = this.$store.state.user.userInfo;
      let appId = "";
      let flag = info.appSimpleBeanList.findIndex((item) => {
        return item.appMark == info.currDs;
      });
      if (flag != -1) {
        appId = info.appSimpleBeanList[flag].appId;
      }
      let param = {
        appId: appId,
      };
      queryPostList(param).then(
        (res) => {
          if (res.code == 200) {
            let data = res.data;
            data.map((item) => {
              let obj = {};
              obj.label = item.postName;
              obj.value = item.id;
              arr.push(obj);
            });
            this.post = arr;
            this.nodeConfig.itemArr[5].seleteOption = this.post;
          }
        },
        (error) => {
          this.$message.error(error);
        }
      );
    },
    // 设置选人回显数据
    setStaffData(data) {
      this.handlerArr = [];
      this.postArr = [];
      this.organization = [];
      this.organizationIndex = [];
      this.organizationArr = [];
      if (data) {
        let info = {};
        info.memberName = [];
        info.memberNameArr = [];
        info.memberAccount = [];
        info.workTeamName = [];
        info.workTeam = [];
        info.workTeamNameArr = [];
        info.node4 = [];
        let value = 0;
        data.forEach((item) => {
          if (item.type == 0) {
            //选人
            this.handlerArr.push(item);
            info.memberName.push(item.name);
            info.memberAccount.push(item.code);
          } else if (item.type == 1) {
            item.value = value;
            //选组织
            this.organization.push(item);
            this.organizationIndex.push(value);
            value++;
          } else if (item.type == 2) {
            //选岗位
            this.postArr.push(item);
            info.node4.push(item.code);
          }
        });
        info.memberName = info.memberName.toString();
        info.memberAccount = info.memberAccount.toString();
        info.memberNameArr = info.memberName.toString();
        this.handler = this.getOptionData(info.memberName, info.memberAccount);
        setTimeout(() => {
          this.$refs.nodeForm.setItemOption("memberName", this.handler);
        }, 0);
        this.nodeFormData = Object.assign(this.nodeFormData, info);
      }
    },
    //设置组织人员选择的数据
    getOptionData(nameStr, idStr) {
      let option = [];
      let nameArr = nameStr == null ? [] : nameStr.split(",");
      let idArr = idStr == null ? [] : idStr.split(",");
      nameArr.map((i, index) => {
        let item = {
          label: i,
          value: idArr[index],
        };
        if (item.label != "") {
          option.push(item);
        }
      });
      return option;
    },
    // 保存
    async save() {
      let obj = this.basicFormData;
      await addOrSaveInfo(obj).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.description);
          this.getDetails();
        }
      });
    },
    // 删除
    async delete() {
      let val = { id: this.id };
      this.$confirm(`是否确认删除`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteInfo(val).then(async (res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.updateListData();
              setTimeout(() => {
                window.close();
              }, 1000);
            }
          });
        })
        .catch((e) => {});
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
  },
};
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  background-color: #ffffff;
  .node {
    margin: 0 30px;
  }
  .title {
    font-size: 14px;
    font-weight: 500;
    color: #000;
    background: #f2f2f2;
    padding: 4px 10px;
    border-radius: 14px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
  }
  .info-data {
    width: 80%;
    margin: 0 auto;
  }
  .node-info {
    width: 100%;
    height: 100%;
    background: #fff;
    .label-text {
      text-align: left;
    }
    .label-text:before {
      display: inline-block;
      content: "";
      margin-right: 12px;
      width: 3px;
      height: 28px;
      background-color: #0d60b4;
    }
    .left {
      background: #fff;
      height: 100%;
      padding: 20px;
      margin: 10px;
      border: 1px #ccc solid;
      border-radius: 8px;
      .work-type {
        margin-top: 20px;
      }
      /deep/ .show-item tbody .el-table__row:first-child {
        background: #eaf4ff;
      }
    }
    .right {
      background: #fff;
      padding: 20px;
      height: 100%;
      margin: 10px;
      border: 1px #ccc solid;
      border-radius: 8px;
      .label-table {
        text-align: right;
        vertical-align: middle;
        float: left;
        font-size: 14px;
        color: #606266;
        line-height: 40px;
        padding: 0 12px 0 0;
        box-sizing: border-box;
        width: 180px;
      }
      /deep/ .el-table {
        width: auto !important;
        max-width: auto !important;
      }
      .right-table {
        /deep/ .el-form-item__content {
          text-align: left;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }
        /deep/ .switch .el-switch__label--right span {
          display: inline-block;
          width: 40px;
        }
        /deep/ .switch .el-switch__label--left span {
          display: inline-block;
          width: 40px;
        }
        /deep/ .el-switch__core {
          display: inline-block;
          width: 55px !important;
        }
      }
    }
  }
}
</style>
